//
//  SegmentedUI.swift
//  uiKit-demo
//
//  Created by 陈澎 on 2024/12/24.
//
import UIKit
import Foundation

class MySegmentedUI: UIViewController {
    @objc func sele(seg: UISegmentedControl) {
        print("选择了\(seg.selectedSegmentIndex), 数量：\(seg.numberOfSegments)")
        if seg.selectedSegmentIndex == 3 {
            // at:插入位置 animated: 是否需要动画
            // 标题
            seg.insertSegment(withTitle: "按钮5", at: 5, animated: true)
            // 图片
            let img = UIImage(named: "cryImg")?.withRenderingMode(UIImage.RenderingMode.alwaysOriginal)
            seg.insertSegment(with: img, at: 4, animated: true)
        } else if seg.selectedSegmentIndex == 2 {
            // 删除
            seg.removeSegment(at: 4, animated: true)
        } else if seg.selectedSegmentIndex == 1 {
            // 修改
            let img = UIImage(named: "happyImg")?.withRenderingMode(UIImage.RenderingMode.alwaysOriginal)
            seg.setImage(img, forSegmentAt: 4)
            seg.setTitle("删除所有", forSegmentAt: 5)
            // 修改宽度
//            seg.setWidth(80, forSegmentAt: 5)
        }
    }
    func render(_ self: AnyObject, target: Any) {
        let segmentedCtrl = UISegmentedControl(items: ["按钮1", "修改", "删除", "添加"])
        // 控件位置与尺寸
        segmentedCtrl.frame = CGRect(x: 20, y: 1020, width: 350, height: 30)
        // 控件风格颜色
        segmentedCtrl.tintColor = UIColor.blue
        // 设置成true，则抬起时会还原，不再选中
        segmentedCtrl.isMomentary = true
        // 根据内容自适应宽度
        segmentedCtrl.apportionsSegmentWidthsByContent = true
        segmentedCtrl.addTarget(target, action: #selector(MySegmentedUI.sele), for: UIControl.Event.valueChanged)
        self.addSubview(segmentedCtrl)
    }
}
